import os
import shutil
import gzip
import sys
from netrc import netrc
import requests
from requests.utils import get_netrc_auth
from datetime import datetime, timedelta
from tqdm import tqdm

# satellite = "lageos1"
satellite = "larets"
# satellite = "ajisai"
organ = "COD"
# organ = "GFZ"
beginDate = "2023-01-01"
endDate = "2025-08-10"
dataFINDir = "../dataset/dataFIN/"
dataRAPDir = "../dataset/dataRAP/"
dataSULTDir = "../dataset/dataSULT/"
dateList = []
dataType = 2
overWrite = False

def get_file_paths(directory):
    file_paths = []
    for root, dirs, files in os.walk(directory):
        for file in files:
            file_path = os.path.join(root, file)
            file_paths.append(os.path.normpath(file_path))
    return file_paths

def date2gpsweek(date):
    # GPS 起始纪元
    gps_epoch = datetime(1980, 1, 6, 0, 0, 0)
    # 时间差
    delta = date - gps_epoch
    # GPS 周数
    week = delta.days // 7
    return week

def yeardoy2date(year, doy):
    year = int(year)
    doy = int(doy)
    return datetime(year, 1, 1) + timedelta(days=doy - 1)

def downloadSultRapFin(weeks):
    for week in weeks:
        check_netrc_url = "https://urs.earthdata.nasa.gov"
        if get_netrc_auth(check_netrc_url) !=None:  # 应该返回 ('your_username', 'your_password')
            session = requests.Session()
            url = f"https://cddis.nasa.gov/archive/gnss/products/{week}/"
            list_response = session.get(url+"*?list")
            lines = list_response.text.strip().split('\n')

            tgt_files = [line.split() for line in lines]
            if dataType==0:
                result = [item[0] for item in tgt_files if item and item[0].startswith(organ+"0OPSFIN") and item[0].endswith(".SP3.gz")]
            elif dataType==1:
                result = [item[0] for item in tgt_files if item and item[0].startswith(organ+"0OPSRAP") and item[0].endswith(".SP3.gz")]
            elif dataType==2:
                result = [item[0] for item in tgt_files if item and item[0].startswith(organ+"0OPSULT") and item[0].endswith(".SP3.gz")]
            else:
                print("data not found")
                sys.exit(0)

            t_bar = tqdm(result, total=len(result))
            for tgt_name in t_bar:
                t_bar.set_description(f"{week}")
                date = tgt_name.split('_')[1]
                date = yeardoy2date(date[:4], date[4:7])
                if date< beginDateTime or date> endDateTime:
                    continue
                if dataType==0:
                    fileName = dataFINDir + tgt_name
                elif dataType==1:
                    fileName = dataRAPDir + tgt_name
                elif dataType==2:
                    fileName = dataSULTDir + tgt_name
                else:
                    print("data not found")
                    sys.exit(0)

                file_response = requests.get(url+tgt_name)
                with open(fileName, 'wb') as fd:
                    for chunk in file_response.iter_content():
                        fd.write(chunk)
                    fd.close()
        else:
            print("没有找到相应的netrc登录信息")
            break

if __name__ == "__main__":
    if overWrite and dataType == 0:
        if os.path.exists(dataFINDir):
            shutil.rmtree(dataFINDir)
        if not os.path.exists(dataFINDir):
            os.mkdir(dataFINDir)
    if overWrite and dataType == 1:
        if os.path.exists(dataRAPDir):
            shutil.rmtree(dataRAPDir)
        if not os.path.exists(dataRAPDir):
            os.mkdir(dataRAPDir)
    if overWrite and dataType == 2:
        if os.path.exists(dataSULTDir):
            shutil.rmtree(dataSULTDir)
        if not os.path.exists(dataSULTDir):
            os.mkdir(dataSULTDir)

    beginDateTime = datetime.strptime(beginDate, "%Y-%m-%d")
    endDateTime = datetime.strptime(endDate, "%Y-%m-%d")

    if dataType == 0:
        fileList = get_file_paths(dataFINDir)
    elif dataType == 1:
        fileList = get_file_paths(dataRAPDir)
    elif dataType == 2:
        fileList = get_file_paths(dataSULTDir)
    else:
        print("data not found")
        sys.exit(0)

    for fileName in fileList:
        date = fileName.split('_')[1]
        date = yeardoy2date(date[:4],date[4:7])
        beginDateTime = max(beginDateTime,date)
        endDateTime = max(endDateTime,date)
    beginDateTime = beginDateTime - timedelta(days=1)
    beginWeek = date2gpsweek(beginDateTime)
    endWeek = date2gpsweek(endDateTime)
    weeks = list(range(beginWeek,endWeek+1))
    if dataType==0 or dataType==1 or dataType==2:
        downloadSultRapFin(weeks)
    else:
        print("data not found")
        sys.exit(0)

    if dataType == 0:
        fileList = get_file_paths(dataFINDir)
    elif dataType == 1:
        fileList = get_file_paths(dataRAPDir)
    elif dataType == 2:
        fileList = get_file_paths(dataSULTDir)

    t_bar = tqdm(fileList,total=len(fileList))
    for fileName in t_bar:
        if os.path.exists(fileName):
            if fileName.endswith(".gz"):
                with gzip.open(fileName, 'rb') as file_in:
                    with open(fileName[:-3], 'wb') as file_out:
                        shutil.copyfileobj(file_in, file_out)
                os.remove(fileName)
